package com.maodou.core.ui.components.textfield

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.*
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import java.util.regex.Pattern

/**
 * 输入框类型枚举
 */
enum class TextFieldType {
    Text,           // 普通文本
    Email,          // 邮箱
    Phone,          // 手机号
    Number,         // 数字
    Decimal,        // 小数
    Password,       // 密码
    Search,         // 搜索
    Multiline,      // 多行文本
    Url,            // 网址
    IdCard,         // 身份证号
    BankCard        // 银行卡号
}

/**
 * 输入验证结果
 */
data class ValidationResult(
    val isValid: Boolean,
    val errorMessage: String? = null
)

/**
 * 输入验证器接口
 */
fun interface InputValidator {
    fun validate(input: String): ValidationResult
}

/**
 * 预定义的输入验证器
 */
object Validators {
    val email = InputValidator { input ->
        if (input.isEmpty()) {
            ValidationResult(true)
        } else {
            val emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
            val isValid = Pattern.matches(emailPattern, input)
            ValidationResult(isValid, if (!isValid) "请输入有效的邮箱地址" else null)
        }
    }
    
    val phone = InputValidator { input ->
        if (input.isEmpty()) {
            ValidationResult(true)
        } else {
            val phonePattern = "^1[3-9]\\d{9}$"
            val isValid = Pattern.matches(phonePattern, input)
            ValidationResult(isValid, if (!isValid) "请输入有效的手机号码" else null)
        }
    }
    
    val idCard = InputValidator { input ->
        if (input.isEmpty()) {
            ValidationResult(true)
        } else {
            val idCardPattern = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$"
            val isValid = Pattern.matches(idCardPattern, input)
            ValidationResult(isValid, if (!isValid) "请输入有效的身份证号码" else null)
        }
    }
    
    val bankCard = InputValidator { input ->
        if (input.isEmpty()) {
            ValidationResult(true)
        } else {
            val cleanInput = input.replace(" ", "")
            val isValid = cleanInput.length in 16..19 && cleanInput.all { it.isDigit() }
            ValidationResult(isValid, if (!isValid) "请输入有效的银行卡号" else null)
        }
    }
    
    val url = InputValidator { input ->
        if (input.isEmpty()) {
            ValidationResult(true)
        } else {
            val urlPattern = "^(https?|ftp)://[^\\s/$.?#].[^\\s]*$"
            val isValid = Pattern.matches(urlPattern, input)
            ValidationResult(isValid, if (!isValid) "请输入有效的网址" else null)
        }
    }
    
    fun required(message: String = "此字段为必填项") = InputValidator { input ->
        ValidationResult(input.isNotBlank(), if (input.isBlank()) message else null)
    }
    
    fun minLength(length: Int, message: String? = null) = InputValidator { input ->
        val isValid = input.length >= length
        ValidationResult(isValid, if (!isValid) (message ?: "最少需要${length}个字符") else null)
    }
    
    fun maxLength(length: Int, message: String? = null) = InputValidator { input ->
        val isValid = input.length <= length
        ValidationResult(isValid, if (!isValid) (message ?: "最多只能输入${length}个字符") else null)
    }
    
    fun range(min: Int, max: Int, message: String? = null) = InputValidator { input ->
        val isValid = input.length in min..max
        ValidationResult(isValid, if (!isValid) (message ?: "字符长度应在${min}-${max}之间") else null)
    }
}

/**
 * 通用的OutlinedTextField组件
 */
@Composable
fun AppTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    label: String? = null,
    placeholder: String? = null,
    leadingIcon: ImageVector? = null,
    trailingIcon: ImageVector? = null,
    onTrailingIconClick: (() -> Unit)? = null,
    supportingText: String? = null,
    isError: Boolean = false,
    errorMessage: String? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    singleLine: Boolean = true,
    maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
    minLines: Int = 1,
    maxLength: Int? = null,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    textStyle: TextStyle = LocalTextStyle.current,
    colors: TextFieldColors = OutlinedTextFieldDefaults.colors(),
    visualTransformation: VisualTransformation = VisualTransformation.None,
    validator: InputValidator? = null,
    validateOnChange: Boolean = true,
    focusRequester: FocusRequester? = null,
    borderless: Boolean = true
) {
    var validationResult by remember { mutableStateOf(ValidationResult(true)) }
    
    // 验证输入
    LaunchedEffect(value) {
        if (validateOnChange && validator != null) {
            validationResult = validator.validate(value)
        }
    }
    
    val finalIsError = isError || !validationResult.isValid
    val finalErrorMessage = errorMessage ?: validationResult.errorMessage
    
    // 根据borderless参数选择合适的颜色配置
    val finalColors = if (borderless) {
        TextFieldDefaults.colors(
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent,
            disabledIndicatorColor = Color.Transparent,
            errorIndicatorColor = Color.Transparent,
            focusedContainerColor = Color.Transparent,
            unfocusedContainerColor = Color.Transparent,
            disabledContainerColor = Color.Transparent,
            errorContainerColor = Color.Transparent
        )
    } else {
        colors
    }
    
    Column(modifier = modifier) {
        if (borderless) {
            // 无边框模式使用TextField
            TextField(
                value = value,
                onValueChange = { newValue ->
                    val filteredValue = if (maxLength != null && newValue.length > maxLength) {
                        newValue.take(maxLength)
                    } else {
                        newValue
                    }
                    onValueChange(filteredValue)
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .let { mod ->
                        if (focusRequester != null) mod.focusRequester(focusRequester) else mod
                    },
                placeholder = placeholder?.let { { Text(it, style = textStyle.copy(color = Color(0xffaaaaaa))) } },
                leadingIcon = leadingIcon?.let { icon ->
                    { Icon(imageVector = icon, contentDescription = null) }
                },
                trailingIcon = trailingIcon?.let { icon ->
                    {
                        if (onTrailingIconClick != null) {
                            IconButton(onClick = onTrailingIconClick) {
                                Icon(imageVector = icon, contentDescription = null)
                            }
                        } else {
                            Icon(imageVector = icon, contentDescription = null)
                        }
                    }
                },
                enabled = enabled,
                readOnly = readOnly,
                singleLine = singleLine,
                maxLines = maxLines,
                minLines = minLines,
                keyboardOptions = keyboardOptions,
                keyboardActions = keyboardActions,
                textStyle = textStyle,
                visualTransformation = visualTransformation,
                colors = finalColors
            )
        } else {
            // 有边框模式使用OutlinedTextField
            OutlinedTextField(
                value = value,
                onValueChange = { newValue ->
                    val filteredValue = if (maxLength != null && newValue.length > maxLength) {
                        newValue.take(maxLength)
                    } else {
                        newValue
                    }
                    onValueChange(filteredValue)
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .let { mod ->
                        if (focusRequester != null) mod.focusRequester(focusRequester) else mod
                    },
                label = label?.let { { Text(it) } },
                placeholder = placeholder?.let { { Text(it) } },
                leadingIcon = leadingIcon?.let { icon ->
                    { Icon(imageVector = icon, contentDescription = null) }
                },
                trailingIcon = trailingIcon?.let { icon ->
                    {
                        if (onTrailingIconClick != null) {
                            IconButton(onClick = onTrailingIconClick) {
                                Icon(imageVector = icon, contentDescription = null)
                            }
                        } else {
                            Icon(imageVector = icon, contentDescription = null)
                        }
                    }
                },
                supportingText = {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = when {
                                finalIsError && finalErrorMessage != null -> finalErrorMessage
                                supportingText != null -> supportingText
                                else -> ""
                            },
                            color = if (finalIsError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        
                        if (maxLength != null) {
                            Text(
                                text = "${value.length}/$maxLength",
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }
                },
                isError = finalIsError,
                enabled = enabled,
                readOnly = readOnly,
                singleLine = singleLine,
                maxLines = maxLines,
                minLines = minLines,
                keyboardOptions = keyboardOptions,
                keyboardActions = keyboardActions,
                textStyle = textStyle,
                visualTransformation = visualTransformation,
                colors = finalColors
            )
        }
        
        // 为无边框模式添加supportingText显示
//        if (borderless && (finalErrorMessage != null || supportingText != null || maxLength != null)) {
//            Row(
//                modifier = Modifier
//                    .fillMaxWidth()
//                    .padding(start = 16.dp, end = 16.dp, top = 4.dp),
//                horizontalArrangement = Arrangement.SpaceBetween
//            ) {
//                Text(
//                    text = when {
//                        finalIsError && finalErrorMessage != null -> finalErrorMessage
//                        supportingText != null -> supportingText
//                        else -> ""
//                    },
//                    color = if (finalIsError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
//                    style = MaterialTheme.typography.bodySmall
//                )
//
//                if (maxLength != null) {
//                    Text(
//                        text = "${value.length}/$maxLength",
//                        color = MaterialTheme.colorScheme.onSurfaceVariant,
//                        style = MaterialTheme.typography.bodySmall
//                    )
//                }
//            }
//        }
    }
}

/**
 * 根据类型创建特定的TextField
 */
@Composable
fun TypedTextField(
    value: String,
    onValueChange: (String) -> Unit,
    type: TextFieldType,
    modifier: Modifier = Modifier,
    label: String? = null,
    placeholder: String? = null,
    supportingText: String? = null,
    isError: Boolean = false,
    errorMessage: String? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    maxLength: Int? = null,
    validator: InputValidator? = null,
    focusRequester: FocusRequester? = null,
    textStyle: TextStyle? = null,
    borderless: Boolean = false
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    
    val (keyboardOptions, visualTransformation, leadingIcon, trailingIcon, defaultValidator, defaultMaxLength) = when (type) {
        TextFieldType.Email -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Email, imeAction = ImeAction.Done),
                VisualTransformation.None,
                if(!borderless) Icons.Default.Email else null,
                null,
                Validators.email,
                null
            )
        }
        TextFieldType.Phone -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Phone, imeAction = ImeAction.Done),
                VisualTransformation.None,
                Icons.Default.Phone,
                null,
                Validators.phone,
                11
            )
        }
        TextFieldType.Number -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
                VisualTransformation.None,
                null,
                null,
                null,
                null
            )
        }
        TextFieldType.Decimal -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Decimal, imeAction = ImeAction.Done),
                VisualTransformation.None,
                null,
                null,
                null,
                null
            )
        }
        TextFieldType.Password -> {
            val passwordVisible by remember { mutableStateOf(false) }
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
                if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                Icons.Default.Lock,
                if (passwordVisible) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                null,
                null
            )
        }
        TextFieldType.Search -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Search),
                VisualTransformation.None,
                Icons.Default.Search,
                if (value.isNotEmpty()) Icons.Default.Clear else null,
                null,
                null
            )
        }
        TextFieldType.Multiline -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Default),
                VisualTransformation.None,
                null,
                null,
                null,
                null
            )
        }
        TextFieldType.Url -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
                VisualTransformation.None,
                null,
                null,
                Validators.url,
                null
            )
        }
        TextFieldType.IdCard -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Done),
                VisualTransformation.None,
                null,
                null,
                Validators.idCard,
                18
            )
        }
        TextFieldType.BankCard -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
                BankCardVisualTransformation(),
                null,
                null,
                Validators.bankCard,
                19
            )
        }
        else -> {
            Tuple6(
                KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Done),
                VisualTransformation.None,
                null,
                null,
                null,
                null
            )
        }
    }
    
    AppTextField(
        value = value,
        onValueChange = { newValue ->
            val filteredValue = when (type) {
                TextFieldType.Number -> newValue.filter { it.isDigit() }
                TextFieldType.Decimal -> {
                    val decimalPattern = "^\\d*\\.?\\d*$"
                    if (newValue.matches(Regex(decimalPattern))) newValue else value
                }
                TextFieldType.Phone -> newValue.filter { it.isDigit() }
                TextFieldType.BankCard -> newValue.filter { it.isDigit() || it == ' ' }
                else -> newValue
            }
            onValueChange(filteredValue)
        },
        modifier = modifier,
        label = label,
        placeholder = placeholder,
        leadingIcon = leadingIcon,
        trailingIcon = trailingIcon,
        onTrailingIconClick = when (type) {
            TextFieldType.Password -> {
                // 密码可见性切换逻辑需要在外部处理
                null
            }
            TextFieldType.Search -> {
                if (value.isNotEmpty()) {{ onValueChange("") }} else null
            }
            else -> null
        },
        borderless = borderless,
        supportingText = supportingText,
        isError = isError,
        errorMessage = errorMessage,
        enabled = enabled,
        readOnly = readOnly,
        singleLine = type != TextFieldType.Multiline,
        maxLines = if (type == TextFieldType.Multiline) Int.MAX_VALUE else 1,
        minLines = if (type == TextFieldType.Multiline) 3 else 1,
        maxLength = maxLength ?: defaultMaxLength,
        keyboardOptions = keyboardOptions,
        keyboardActions = KeyboardActions(
            onDone = { keyboardController?.hide() },
            onSearch = { keyboardController?.hide() }
        ),
        textStyle = textStyle ?: LocalTextStyle.current,
        validator = validator ?: defaultValidator,
        focusRequester = focusRequester
    )
}

/**
 * 银行卡号格式化显示（每4位加空格）
 */
class BankCardVisualTransformation : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        val trimmed = text.text.replace(" ", "")
        val formatted = buildString {
            trimmed.forEachIndexed { index, char ->
                if (index > 0 && index % 4 == 0) {
                    append(" ")
                }
                append(char)
            }
        }
        
        val offsetMapping = object : OffsetMapping {
            override fun originalToTransformed(offset: Int): Int {
                return offset + (offset / 4)
            }
            
            override fun transformedToOriginal(offset: Int): Int {
                return offset - (offset / 5)
            }
        }
        
        return TransformedText(AnnotatedString(formatted), offsetMapping)
    }
}

/**
 * 搜索框组件
 */
@Composable
fun SearchField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    placeholder: String = "搜索...",
    onSearch: ((String) -> Unit)? = null,
    enabled: Boolean = true,
    focusRequester: FocusRequester? = null,
    borderless: Boolean = false
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    
    AppTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier,
        placeholder = placeholder,
        leadingIcon = Icons.Default.Search,
        trailingIcon = if (value.isNotEmpty()) Icons.Default.Clear else null,
        onTrailingIconClick = if (value.isNotEmpty()) {{ onValueChange("") }} else null,
        enabled = enabled,
        singleLine = true,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Text,
            imeAction = ImeAction.Search
        ),
        keyboardActions = KeyboardActions(
            onSearch = {
                onSearch?.invoke(value)
                keyboardController?.hide()
            }
        ),
        focusRequester = focusRequester,
        borderless = borderless
    )
}

/**
 * 表单输入框组件
 */
@Composable
fun FormField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String,
    modifier: Modifier = Modifier,
    placeholder: String? = null,
    required: Boolean = false,
    type: TextFieldType = TextFieldType.Text,
    maxLength: Int? = null,
    supportingText: String? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    validator: InputValidator? = null,
    focusRequester: FocusRequester? = null,
    textStyle: TextStyle? = null,
    borderless: Boolean = false
) {
    val finalLabel = if (required) "$label *" else label
    val finalValidator = if (required && validator == null) {
        Validators.required("${label}为必填项")
    } else {
        validator
    }
    
    TypedTextField(
        value = value,
        onValueChange = onValueChange,
        type = type,
        modifier = modifier,
        label = finalLabel,
        placeholder = placeholder,
        supportingText = supportingText,
        enabled = enabled,
        readOnly = readOnly,
        maxLength = maxLength,
        validator = finalValidator,
        textStyle = textStyle,
        focusRequester = focusRequester,
        borderless = borderless
    )
}

/**
 * 多行文本输入框
 */
@Composable
fun MultilineTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    label: String? = null,
    placeholder: String? = null,
    minLines: Int = 3,
    maxLines: Int = 8,
    maxLength: Int? = null,
    supportingText: String? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    validator: InputValidator? = null,
    focusRequester: FocusRequester? = null,
    borderless: Boolean = false
) {
    AppTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier,
        label = label,
        placeholder = placeholder,
        supportingText = supportingText,
        enabled = enabled,
        readOnly = readOnly,
        singleLine = false,
        minLines = minLines,
        maxLines = maxLines,
        maxLength = maxLength,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Text,
            imeAction = ImeAction.Default
        ),
        validator = validator,
        focusRequester = focusRequester,
        borderless = borderless
    )
}

/**
 * 密码输入框
 */
@Composable
fun PasswordField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    label: String = "密码",
    placeholder: String? = null,
    supportingText: String? = null,
    enabled: Boolean = true,
    maxLength: Int? = null,
    validator: InputValidator? = null,
    focusRequester: FocusRequester? = null,
    borderless: Boolean = false
) {
    var passwordVisible by remember { mutableStateOf(false) }
    val keyboardController = LocalSoftwareKeyboardController.current
    
    AppTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier,
        label = label,
        placeholder = placeholder,
        leadingIcon = Icons.Default.Lock,
        trailingIcon = if (passwordVisible) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
        onTrailingIconClick = { passwordVisible = !passwordVisible },
        supportingText = supportingText,
        enabled = enabled,
        singleLine = true,
        maxLength = maxLength,
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Password,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = { keyboardController?.hide() }
        ),
        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
        validator = validator,
        focusRequester = focusRequester,
        borderless = borderless
    )
}

/**
 * 无边框输入框组件（基于TextField）
 */
@Composable
fun BorderlessTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    placeholder: String? = null,
    leadingIcon: ImageVector? = null,
    trailingIcon: ImageVector? = null,
    onTrailingIconClick: (() -> Unit)? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    singleLine: Boolean = true,
    maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
    minLines: Int = 1,
    maxLength: Int? = null,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    textStyle: TextStyle = LocalTextStyle.current,
    colors: TextFieldColors = TextFieldDefaults.colors(
        focusedIndicatorColor = Color.Transparent,
        unfocusedIndicatorColor = Color.Transparent,
        disabledIndicatorColor = Color.Transparent,
        errorIndicatorColor = Color.Transparent,
        focusedContainerColor = Color.Transparent,
        unfocusedContainerColor = Color.Transparent,
        disabledContainerColor = Color.Transparent,
        errorContainerColor = Color.Transparent
    ),
    validator: InputValidator? = null,
    validateOnChange: Boolean = true,
    focusRequester: FocusRequester? = null
) {
    var validationResult by remember { mutableStateOf(ValidationResult(true)) }
    
    // 验证输入
    LaunchedEffect(value) {
        if (validateOnChange && validator != null) {
            validationResult = validator.validate(value)
        }
    }
    
    TextField(
        value = value,
        onValueChange = { newValue ->
            val filteredValue = if (maxLength != null && newValue.length > maxLength) {
                newValue.take(maxLength)
            } else {
                newValue
            }
            onValueChange(filteredValue)
        },
        modifier = modifier
            .fillMaxWidth()
            .let { mod ->
                if (focusRequester != null) mod.focusRequester(focusRequester) else mod
            },
        placeholder = placeholder?.let { { Text(it) } },
        leadingIcon = leadingIcon?.let { icon ->
            { Icon(imageVector = icon, contentDescription = null) }
        },
        trailingIcon = trailingIcon?.let { icon ->
            {
                if (onTrailingIconClick != null) {
                    IconButton(onClick = onTrailingIconClick) {
                        Icon(imageVector = icon, contentDescription = null)
                    }
                } else {
                    Icon(imageVector = icon, contentDescription = null)
                }
            }
        },
        enabled = enabled,
        readOnly = readOnly,
        singleLine = singleLine,
        maxLines = maxLines,
        minLines = minLines,
        keyboardOptions = keyboardOptions,
        keyboardActions = keyboardActions,
        textStyle = textStyle,
        colors = colors
    )
}

/**
 * 类型化无边框输入框
 */
@Composable
fun TypedBorderlessTextField(
    value: String,
    onValueChange: (String) -> Unit,
    type: TextFieldType,
    modifier: Modifier = Modifier,
    placeholder: String? = null,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    maxLength: Int? = null,
    validator: InputValidator? = null,
    focusRequester: FocusRequester? = null
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    
    val (keyboardOptions, leadingIcon, trailingIcon, defaultValidator, defaultMaxLength) = when (type) {
        TextFieldType.Email -> {
            Tuple5(
                KeyboardOptions(keyboardType = KeyboardType.Email, imeAction = ImeAction.Done),
                Icons.Default.Email,
                null,
                Validators.email,
                null
            )
        }
        TextFieldType.Phone -> {
            Tuple5(
                KeyboardOptions(keyboardType = KeyboardType.Phone, imeAction = ImeAction.Done),
                Icons.Default.Phone,
                null,
                Validators.phone,
                11
            )
        }
        TextFieldType.Number -> {
            Tuple5(
                KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
                null,
                null,
                null,
                null
            )
        }
        TextFieldType.Search -> {
            Tuple5(
                KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Search),
                Icons.Default.Search,
                if (value.isNotEmpty()) Icons.Default.Clear else null,
                null,
                null
            )
        }
        TextFieldType.Password -> {
            Tuple5(
                KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
                Icons.Default.Lock,
                Icons.Default.FavoriteBorder,
                null,
                null
            )
        }
        else -> {
            Tuple5(
                KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Done),
                null,
                null,
                null,
                null
            )
        }
    }
    
    BorderlessTextField(
        value = value,
        onValueChange = { newValue ->
            val filteredValue = when (type) {
                TextFieldType.Number -> newValue.filter { it.isDigit() }
                TextFieldType.Phone -> newValue.filter { it.isDigit() }
                else -> newValue
            }
            onValueChange(filteredValue)
        },
        modifier = modifier,
        placeholder = placeholder,
        leadingIcon = leadingIcon,
        trailingIcon = trailingIcon,
        onTrailingIconClick = when (type) {
            TextFieldType.Search -> {
                if (value.isNotEmpty()) {{ onValueChange("") }} else null
            }
            else -> null
        },
        enabled = enabled,
        readOnly = readOnly,
        singleLine = type != TextFieldType.Multiline,
        maxLines = if (type == TextFieldType.Multiline) Int.MAX_VALUE else 1,
        minLines = if (type == TextFieldType.Multiline) 3 else 1,
        maxLength = maxLength ?: defaultMaxLength,
        keyboardOptions = keyboardOptions,
        keyboardActions = KeyboardActions(
            onDone = { keyboardController?.hide() },
            onSearch = { keyboardController?.hide() }
        ),
        validator = validator ?: defaultValidator,
        focusRequester = focusRequester
    )
}

// 辅助数据类
data class Tuple5<A, B, C, D, E>(
    val first: A,
    val second: B,
    val third: C,
    val fourth: D,
    val fifth: E
)

data class Tuple6<A, B, C, D, E, F>(
    val first: A,
    val second: B,
    val third: C,
    val fourth: D,
    val fifth: E,
    val sixth: F
)

// 预览组件
@Preview(showBackground = true)
@Composable
fun TextFieldsPreview() {
    MaterialTheme {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            var text by remember { mutableStateOf("") }
            var email by remember { mutableStateOf("") }
            var phone by remember { mutableStateOf("") }
            var password by remember { mutableStateOf("") }
            var search by remember { mutableStateOf("") }
            var multiline by remember { mutableStateOf("") }
            
            Text(
                text = "输入框组件示例",
                style = MaterialTheme.typography.headlineSmall
            )
            
            AppTextField(
                value = text,
                onValueChange = { text = it },
                label = "普通文本",
                placeholder = "请输入文本",
                maxLength = 50
            )
            
            TypedTextField(
                value = email,
                onValueChange = { email = it },
                type = TextFieldType.Email,
                label = "邮箱地址",
                placeholder = "请输入邮箱"
            )
            
            TypedTextField(
                value = phone,
                onValueChange = { phone = it },
                type = TextFieldType.Phone,
                label = "手机号码",
                placeholder = "请输入手机号"
            )
            
            PasswordField(
                value = password,
                onValueChange = { password = it },
                label = "密码",
                placeholder = "请输入密码"
            )
            
            SearchField(
                value = search,
                onValueChange = { search = it },
                placeholder = "搜索内容"
            )
            
            MultilineTextField(
                value = multiline,
                onValueChange = { multiline = it },
                label = "多行文本",
                placeholder = "请输入多行文本",
                maxLength = 200
            )
        }
    }
}